Python 24-Day CourseDay 18pythonintermediate
Python 24-Day Course - Day 18: HTTP Requests
· 2 min read
Day 18: HTTP Requests
Installing the requests Library
pip install requests
GET Request
import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(response.status_code) # 200
print(response.headers["content-type"])
data = response.json()
print(data["title"])
HTTP Methods
| Method | Purpose | requests Function |
|---|
| GET | Retrieve data | requests.get() |
| POST | Create data | requests.post() |
| PUT | Update data (full) | requests.put() |
| PATCH | Update data (partial) | requests.patch() |
| DELETE | Delete data | requests.delete() |
POST Request
new_post = {
"title": "New Post",
"body": "Sending HTTP requests from Python",
"userId": 1
}
response = requests.post(
"https://jsonplaceholder.typicode.com/posts",
json=new_post
)
print(response.status_code) # 201
print(response.json()["id"])
Query Parameters and Headers
# Query parameters
params = {"userId": 1, "_limit": 5}
response = requests.get(
"https://jsonplaceholder.typicode.com/posts",
params=params
)
# Custom headers
headers = {
"Authorization": "Bearer YOUR_TOKEN",
"Content-Type": "application/json"
}
response = requests.get(url, headers=headers)
Error Handling
def fetch_data(url):
try:
response = requests.get(url, timeout=10)
response.raise_for_status() # Raises exception for 4xx, 5xx errors
return response.json()
except requests.exceptions.Timeout:
print("Request timed out")
except requests.exceptions.HTTPError as e:
print(f"HTTP error: {e}")
except requests.exceptions.ConnectionError:
print("Cannot connect to server")
return None
Today’s Exercises
- Write a program that fetches weather data from a public API and displays it.
- Use the GitHub API to retrieve a specific user’s repository list.
- Create a function that fetches data sequentially from multiple URLs and merges it.
Was this article helpful?
Thanks for your feedback!